import store from "@/store/index.js";
var Fly=require("flyio/dist/npm/wx")
var fly=new Fly
fly.config.timeout = 5000; // 超时
//添加请求拦截器
fly.interceptors.request.use((request)=>{
  //给所有请求添加自定义header
  //终止请求
  //var err=new Error("xxx")
  //err.request=request
  //return Promise.reject(new Error(""))
  let sessionId = ﻿uni.getStorageSync('sessionId');
  if(sessionId){
    request.headers.Cookie = "frontend="+sessionId;
  }
  // if(store.state.sessionId !== ""){
  //   request.headers.Cookie = "frontend="+store.state.sessionId;
  // }
  let token = ﻿uni.getStorageSync('token');
  if(token){
    request.headers.token = token;
  }
  //可以显式返回request, 也可以不返回，没有返回值时拦截器中默认返回request
  return request;
})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (data) => {
    if (data.data != null && typeof data.data === "object") {
      if (data.data.success && data.data.data.status === 200) {
        return data.data.data.data;
      } else {
        if (!data.data.success) {
          return Promise.reject(data.data.message);
        } else {
          if (data.data.data.status === 201) {
            let token = ﻿uni.getStorageSync('token');
            store.dispatch('changeLoginStatus',false)
            if(token){
              ﻿uni.removeStorageSync('token')
              ﻿uni.showModal({
                title: '亲，你的账号已过期',
                content: '请重新登录~',
                success (res) {
                  if (res.confirm) {
                    ﻿uni.navigateTo({
                      url: '/person/login'
                    })
                  }
                }
              });
            } else {
              ﻿uni.showModal({
                title: '亲，你尚未登录',
                content: '前去登录吧~',
                success (res) {
                  if (res.confirm) {
                    ﻿uni.navigateTo({
                      url: '/person/login'
                    })
                  }
                }
              });
              return Promise.reject(data.data.data.msg);
            }
          } else if(data.data.data.status === 223){
            store.dispatch('changeAth',false)
            return Promise.reject(data.data.data.msg);
          } else {
            return Promise.reject(data.data.data.msg);
          }
        }
      }
    }
  },
  (err) => {
    //发生网络错误后会走到这里
    console.log(err)
    let errmsg = ''
    errmsg = '请求超时，请重新加载'
    return Promise.reject(errmsg)
  }
)
export default {
  post(url, data, options) {
    return fly.post(url, data, options);
  },
  // get方法
  get(url, data, options) {
    return fly.get(url, data, options);
  }
};
